#include "HighScore.h"
#include <algorithm>
#include <iomanip>
#include <conio.h>
#include <fstream>
#include <sstream>
using namespace std;

HighScore::HighScore()
{
	numScores = 10;
}


HighScore::~HighScore()
{
}

void HighScore::addScore(string name, int score)
{
	highScores.push_back(HighScoreData(name, score));
	manageScores();
}
void HighScore::loadScores(string file)
{
	highScores.clear();
	ifstream fin;
	fin.open(file);
	string strRow;
	while (std::getline(fin, strRow)){
		istringstream iss(strRow);
		string str;
		std::getline(iss, str, '=');
		if (str.compare("highscore") == 0){
			HighScoreData score;
			std::getline(iss, str, '=');
			iss >> score;
			highScores.push_back(score);
		}
	}
	fin.close();
	manageScores();
}
void HighScore::saveScores(string file)
{
	manageScores();
	ofstream fout;
	fout.open(file);
	for (int i = 0; i < highScores.size(); i++){
		fout << "highscore=("<< highScores[i] << ")" << endl;
	}
	fout.close();
}

void HighScore::manageScores()
{
	sort(highScores.begin(), highScores.end());
	if (highScores.size() > numScores){
		highScores.pop_back();
	}
}

void HighScore::print()
{
	cout << ":::::::::HIGHSCORE LIST:::::::::" << endl << endl;
	for (int i = 0; i < highScores.size(); i++){
		cout << "#" << setw(2) << left << i + 1 << "| " << setw(4) << right << highScores[i].getName() << " : " << setw(5) << left << highScores[i].getScore() << endl;
	}
}
int HighScore::getWorstScore()
{
	if (highScores.size() < 10)
	{
		return INT_MAX;
	}
	else
	{
		return highScores[9].getScore();
	}
}

string HighScore::getArcadeName()
{
	char c[4] = { 'A', 'A', 'A', '\0' };
	int cursorPos = 0;
	while (true)
	{
		system("cls");
		cout << "Enter your name:" << endl << endl;
		cout << c[0] << c[1] << c[2] << endl;
		if (cursorPos == 0)
		{
			cout << "^  " << endl;
		}
		else if (cursorPos == 1)
		{
			cout << " ^ " << endl;
		}
		else
		{
			cout << "  ^" << endl;
		}

		char input = _getch();
		//LeftArrow
		if (input == 75)
		{
			if (cursorPos == 0)
			{
				cursorPos = 2;
			}
			else
			{
				cursorPos--;
			}
		}
		//UpArrow
		else if (input == 72)
		{
			if (c[cursorPos] == 'Z')
			{
				c[cursorPos] = 'A';
			}
			else
			{
				c[cursorPos]++;
			}
		}
		//RightArrow
		else if (input == 77)
		{
			if (cursorPos == 2)
			{
				cursorPos = 0;
			}
			else
			{
				cursorPos++;
			}
		}
		//DownArrow
		else if (input == 80)
		{
			if (c[cursorPos] == 'A')
			{
				c[cursorPos] = 'Z';
			}
			else
			{
				c[cursorPos]--;
			}
		}
		else if (input == 13)
		{
			break;
		}
	}
	return c;
}